<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>员工信息管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    }

    body {
        background: #f8fafc;
    }

    .module-section {
        padding: 2rem;
        max-width: 1600px;
        margin: 0 auto;
    }

    /* 卡片样式优化 */
    .card {
        background: white;
        border-radius: 12px;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.02);
        padding: 2rem;
        margin-bottom: 2rem;
        border: 1px solid #e2e8f0;
    }

    .module-title {
        font-size: 1.5rem;
        color: #1e293b;
        margin-bottom: 1.5rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding-bottom: 1rem;
        border-bottom: 1px solid #e2e8f0;
    }

    /* 统计卡片 */
    .stats-container {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .stat-card {
        background: white;
        padding: 1.5rem;
        border-radius: 12px;
        text-align: center;
        border-left: 4px solid #7c3aed;
        transition: transform 0.2s;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    }

    .stat-value {
        font-size: 2rem;
        font-weight: 600;
        color: #1e293b;
        letter-spacing: -0.5px;
    }

    .stat-label {
        color: #64748b;
        font-size: 0.95rem;
        margin-top: 0.75rem;
    }

    /* 表格深度优化 */
    .data-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 14px;
        background: white;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
    }

    .data-table thead {
        background-color: #f8fafc;
        border-bottom: 2px solid #e2e8f0;
    }

    .data-table th {
        padding: 16px 20px;
        text-align: left;
        color: #475569;
        font-weight: 600;
        font-size: 15px;
        white-space: nowrap;
    }

    .data-table td {
        padding: 14px 20px;
        border-bottom: 1px solid #e2e8f0;
        color: #475569;
        line-height: 1.5;
    }

    .data-table tr:last-child td {
        border-bottom: none;
    }

    .data-table tr:hover {
        background-color: #f8fafc;
    }

    /* 操作按钮组 */
    .operation-buttons {
        display: flex;
        gap: 8px;
    }

    .btn-small {
        padding: 8px 12px;
        border: none;
        border-radius: 8px;
        background: transparent;
        cursor: pointer;
        transition: all 0.2s;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        font-size: 14px;
    }

    .btn-small[data-action="edit"] {
        color: #3b82f6;
        border: 1px solid #bfdbfe;
    }

    .btn-small[data-action="edit"]:hover {
        background: #eff6ff;
        border-color: #93c5fd;
    }

    .btn-small[data-action="delete"] {
        color: #ef4444;
        border: 1px solid #fecaca;
    }

    .btn-small[data-action="delete"]:hover {
        background: #fef2f2;
        border-color: #fca5a5;
    }

    /* 表单样式优化 */
    .triple-column-form {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 1.5rem;
        margin-top: 1rem;
    }

    .form-group {
        margin-bottom: 1rem;
        position: relative;
    }

    .form-group label {
        display: block;
        margin-bottom: 0.75rem;
        color: #475569;
        font-weight: 500;
        font-size: 14px;
    }

    input, select, textarea {
        width: 100%;
        padding: 10px 14px;
        border: 1px solid #cbd5e1;
        border-radius: 8px;
        font-size: 14px;
        transition: all 0.2s;
        background: white;
    }

    input:focus, select:focus, textarea:focus {
        border-color: #7c3aed;
        box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.1);
        outline: none;
    }

    .submit-btn {
        background: #7c3aed;
        color: white;
        padding: 12px 24px;
        border: none;
        border-radius: 8px;
        cursor: pointer;
        transition: background 0.2s;
        font-size: 14px;
        font-weight: 500;
    }

    .submit-btn:hover {
        background: #6d28d9;
    }

    .employee-id {
        background: #f8fafc;
        padding: 10px 14px;
        border-radius: 8px;
        font-weight: 500;
        color: #64748b;
        border: 1px solid #e2e8f0;
    }

    /* 响应式适配 */
    @media (max-width: 1280px) {
        .module-section {
            padding: 1.5rem;
        }
        
        .card {
            padding: 1.5rem;
        }
    }

    @media (max-width: 1024px) {
        .triple-column-form {
            grid-template-columns: repeat(2, 1fr);
        }
        
        .data-table {
            font-size: 13px;
        }
    }

    @media (max-width: 768px) {
        .stats-container {
            grid-template-columns: 1fr 1fr;
        }
        
        .triple-column-form {
            grid-template-columns: 1fr;
        }
        
        .data-table {
            display: block;
            overflow-x: auto;
            white-space: nowrap;
        }
        
        .btn-small {
            padding: 6px 10px;
            font-size: 13px;
        }
    }
    </style>
</head>
<body>
    <div class="module-section">
        <!-- 统计卡片 -->
        <div class="stats-container">
            <div class="stat-card">
                <div class="stat-value" id="totalEmployees">0</div>
                <div class="stat-label">在职员工</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="monthlyNewEmployees">0</div>
                <div class="stat-label">本月入职</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="attendanceRate">0%</div>
                <div class="stat-label">出勤率</div>
            </div>
        </div>

        <!-- 员工信息表单 -->
        <div class="card">
            <h2 class="module-title">
                <i class="fas fa-user-tie"></i>
                员工信息管理
            </h2>
            <form id="employeeForm" class="triple-column-form">
                <!-- 原始表单内容完整保留 -->
                <div class="form-group">
                    <label class="required">员工姓名</label>
                    <input type="text" name="name" placeholder="请输入姓名" required>
                </div>
                <div class="form-group">
                    <label class="required">性别</label>
                    <select name="gender" required>
                        <option value="">请选择</option>
                        <option>男</option>
                        <option>女</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>员工编号</label>
                    <div class="employee-id" id="employeeCode"></div>
                </div>

                <div class="form-group">
                    <label class="required">所属部门</label>
                    <select name="department" required>
                        <option value="">请选择部门</option>
                        <option>财务部</option>
                        <option>采购部</option>
                        <option>仓储部</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="required">职位</label>
                    <input type="text" name="position" placeholder="输入职位名称" required>
                </div>
                <div class="form-group">
                    <label class="required">入职日期</label>
                    <input type="date" name="hire_date" required>
                </div>

                <div class="form-group">
                    <label class="required">手机号码</label>
                    <input type="tel" name="phone" pattern="[0-9]{11}" placeholder="11位手机号" required>
                </div>
                <div class="form-group">
                    <label>电子邮箱</label>
                    <input type="email" name="email" placeholder="example@domain.com">
                </div>
                <div class="form-group">
                    <label>紧急联系人</label>
                    <input type="text" name="emergency_contact" placeholder="姓名+联系方式">
                </div>

                <div class="form-group" style="grid-column: span 3">
                    <label>工作经历</label>
                    <textarea name="work_experience" rows="3" placeholder="简要描述工作经历"></textarea>
                </div>

                <div class="form-group" style="grid-column: span 3; text-align: right;">
                    <button type="submit" class="submit-btn">
                        <i class="fas fa-save"></i>
                        保存信息
                    </button>
                </div>
            </form>
        </div>

        <!-- 优化后的员工列表 -->
        <div class="card">
            <h2 class="module-title">
                <i class="fas fa-clipboard-list"></i>
                在职员工列表
            </h2>
            
            <table class="data-table">
                <thead>
                    <tr>
                        <th>工号</th>
                        <th>姓名</th>
                        <th>部门</th>
                        <th>职位</th>
                        <th>联系方式</th>
                        <th>入职时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="employeeTableBody">
                    <tr>
                        <td>EMP2023001</td>
                        <td>王伟</td>
                        <td>财务部</td>
                        <td>会计主管</td>
                        <td>138****5678</td>
                        <td>2023-03-15</td>
                        <td>
                            <div class="operation-buttons">
                                <button class="btn-small" data-action="edit">
                                    <i class="fas fa-edit"></i>
                                    <span>编辑</span>
                                </button>
                                <button class="btn-small" data-action="delete">
                                    <i class="fas fa-trash"></i>
                                    <span>删除</span>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>EMP2023002</td>
                        <td>张丽华</td>
                        <td>技术研发部</td>
                        <td>前端工程师</td>
                        <td>159****8899</td>
                        <td>2023-05-20</td>
                        <td>
                            <div class="operation-buttons">
                                <button class="btn-small" data-action="edit">
                                    <i class="fas fa-edit"></i>
                                    <span>编辑</span>
                                </button>
                                <button class="btn-small" data-action="delete">
                                    <i class="fas fa-trash"></i>
                                    <span>删除</span>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>EMP2023003</td>
                        <td>陈建国</td>
                        <td>市场营销部</td>
                        <td>市场总监</td>
                        <td>136****4321</td>
                        <td>2022-11-01</td>
                        <td>
                            <div class="operation-buttons">
                                <button class="btn-small" data-action="edit">
                                    <i class="fas fa-edit"></i>
                                    <span>编辑</span>
                                </button>
                                <button class="btn-small" data-action="delete">
                                    <i class="fas fa-trash"></i>
                                    <span>删除</span>
                                </button>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 在此处添加员工管理脚本 -->
    <script>
    // 立即初始化员工管理功能
    (function() {
        const form = document.getElementById('employeeForm');
        const employeeCodeElem = document.getElementById('employeeCode');
        const tableBody = document.getElementById('employeeTableBody');
        let editMode = false;
        let currentEditCode = null;

        // 新增：更新在职员工及本月入职统计
        function updateStats(employees) {
            const totalElem = document.getElementById('totalEmployees');
            const newElem = document.getElementById('monthlyNewEmployees');
            totalElem.textContent = employees.length;
            const now = new Date();
            const thisYear = now.getFullYear();
            const thisMonth = now.getMonth() + 1;
            const countNew = employees.filter(emp => {
                const [y, m] = emp.hire_date.split('-').map(Number);
                return y === thisYear && m === thisMonth;
            }).length;
            newElem.textContent = countNew;
        }

        // 根据考勤记录计算总出勤率
        function updateAttendanceRate(employees) {
            const rateElem = document.getElementById('attendanceRate');
            const now = new Date();
            const monthStr = now.toISOString().slice(0,7);
            // 计算当月总天数（包含周末）
            const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
            const workDays = daysInMonth;
            fetch(`/api/attendance-records?month=${monthStr}`)
            .then(res => res.json())
            .then(json => {
                if (json.success) {
                    const records = json.data;
                    const uniqueKeys = new Set(records.map(r => r.code + '_' + r.date));
                    const attendanceDays = uniqueKeys.size;
                    const expected = employees.length * workDays;
                    const rate = expected > 0 ? Math.round(attendanceDays / expected * 100) : 0;
                    rateElem.textContent = rate + '%';
                }
            });
        }

        function fetchEmployees() {
            fetch('/api/employees')
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        // 更新统计数据
                        updateStats(data.data);
                        // 更新出勤率
                        updateAttendanceRate(data.data);
                        tableBody.innerHTML = '';
                        data.data.forEach(emp => {
                            const tr = document.createElement('tr');
                            tr.innerHTML = `
                                <td>${emp.employee_code}</td>
                                <td>${emp.name}</td>
                                <td>${emp.department}</td>
                                <td>${emp.position}</td>
                                <td>${emp.phone}</td>
                                <td>${emp.hire_date}</td>
                                <td>
                                    <div class="operation-buttons">
                                        <button class="btn-small" data-action="edit"><i class="fas fa-edit"></i><span>编辑</span></button>
                                        <button class="btn-small" data-action="delete"><i class="fas fa-trash"></i><span>删除</span></button>
                                    </div>
                                </td>`;
                            tableBody.appendChild(tr);
                        });
                    } else {
                        console.error('获取员工列表失败:', data.message);
                        alert('获取员工列表失败: ' + data.message);
                    }
                })
                .catch(err => {
                    console.error('获取员工列表失败:', err);
                    alert('获取员工列表失败: ' + err.message);
                });
        }

        form.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(form);
            const data = Object.fromEntries(formData.entries());
            const url = editMode ? `/api/employees/${currentEditCode}` : '/api/employees';
            const method = editMode ? 'PUT' : 'POST';
            fetch(url, {
                method: method,
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            })
            .then(res => {
                if (!res.ok) {
                    return res.json().then(errData => {
                        throw new Error(errData.message || `操作失败 (${res.status})`);
                    });
                }
                return res.json();
            })
            .then(resp => {
                if (resp.success) {
                    alert(resp.message || '操作成功');
                    form.reset();
                    employeeCodeElem.textContent = '';
                    editMode = false;
                    currentEditCode = null;
                    // 重新获取员工列表以刷新表格
                    fetchEmployees();
                } else {
                    alert(resp.message || '操作失败');
                    console.error('提交表单失败:', resp);
                }
            })
            .catch(err => {
                alert('请求失败: ' + err.message);
                console.error('请求失败:', err);
            });
        });

        tableBody.addEventListener('click', function(e) {
            if (e.target.closest('button[data-action="edit"]')) {
                const tr = e.target.closest('tr');
                const tds = tr.querySelectorAll('td');
                const code = tds[0].textContent;
                fetch(`/api/employees/${code}`)
                    .then(res => res.json())
                    .then(resp => {
                        if (resp.success) {
                            const emp = resp.data;
                            form.name.value = emp.name;
                            form.gender.value = emp.gender;
                            form.department.value = emp.department;
                            form.position.value = emp.position;
                            form.hire_date.value = emp.hire_date;
                            form.phone.value = emp.phone;
                            form.email.value = emp.email || '';
                            form.emergency_contact.value = emp.emergency_contact || '';
                            form.work_experience.value = emp.work_experience || '';
                            employeeCodeElem.textContent = code;
                            editMode = true;
                            currentEditCode = code;
                        }
                    });
            } else if (e.target.closest('button[data-action="delete"]')) {
                const tr = e.target.closest('tr');
                const code = tr.querySelector('td').textContent;
                if (confirm(`确定删除员工 ${code}？`)) {
                    fetch(`/api/employees/${code}`, {method: 'DELETE'})
                        .then(res => res.json())
                        .then(resp => {
                            alert(resp.message);
                            fetchEmployees();
                        });
                }
            }
        });

        // 加载数据库中的员工信息
        fetchEmployees();
    })();
    </script>
</body>
</html>